package com.weixin.web;

import com.agent.entity.*;
import com.agent.service.*;
import com.agent.util.CommonUtils;
import com.agent.util.Constants;
import com.agent.util.DateUtil;
import com.agent.util.MyPropertiesConfigurer;
import com.agent.util.ResponseData;
import com.sun.javafx.collections.MappingChange;
import com.weixin.pojo.AccessToken;
import com.weixin.pojo.Text;
import com.weixin.pojo.Textcard;
import com.weixin.pojo.WXMsg;
import com.weixin.service.WeixinNotifyService;
import com.weixin.util.QRCodeUtil;
import com.weixin.util.WXUserUtil;
import com.weixin.util.WXUtil;
import com.weixin.util.WxepConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by hg on 2019/1/10.
 */
@RequestMapping(value = "weixin/engineer")
@Controller
@Slf4j
public class EngineerController {
    @Resource(name = "repaireInfoService")
    IRepaireInfoService service;

    @Resource(name = "weixinNotifyService")
    WeixinNotifyService weixinNotifyService;

    @Resource(name = "dictService")
    IDictService dictService;

    @Resource(name = "picWordService")
    IPicWordService picWordService;
    @Resource(name = "userServiceImpl")
    UserService userService;

    @Autowired
    private RepairePicService RepairePicService;

    @RequestMapping("/to_forward")
    public String to_list(@RequestParam("code") String code, @RequestParam("state") String state, Model model,
                          HttpServletRequest request, HttpServletResponse response){
        String userId = WXUserUtil.findCookie(request);
        if("".equals(userId)) {
            AccessToken accessToken = WXUtil.getAccessToken(WxepConstants.CorpId, WxepConstants.ENGINEER_SECRET,0);
            if (accessToken != null) {
                if (accessToken.getExpiresTime() - System.currentTimeMillis() > 0) {
                    try {
                        userId = WXUserUtil.getUserInfo(accessToken.getToken(), code);
                        log.info("com.weixin.web.WXController.toRepair code is {}, userId is {}", code, userId);
                        model.addAttribute("userId", userId);
                        Cookie cookie = new Cookie("userId",userId);
                        cookie.setPath("/");
                        response.addCookie(cookie);
                    } catch (Exception e) {
                        log.error("WXUserUtil.getUserInfo error |", e);
                    }
                }
            }
        }
        if("allocation".equals(state)){
            return "forward:/weixin/allocation/to_allocation?userId="+userId;
        }else if(WxepConstants.LIST.equals(state)){
            return "forward:/weixin/engineer/list?userId="+userId;
        }else if("pending".equals(state)){
            return "forward:/weixin/engineer/pending?userId="+userId;
        }else if("showQr".equals(state)){
            return "forward:/weixin/engineer/showQr?userId="+userId;
        }else if("listAll".equals(state)){
            return "forward:/weixin/engineer/listAll?userId="+userId;
        }else if("cycle".equals(state)){
            return "forward:/weixin/allocation/to_searchCycle?userId="+userId;
        }
        return "";
    }

    /**
     *   进入到详情页
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/repaireDetail/{id}")
    public String repaireDetail(@PathVariable("id") String id,Model model){
        RepaireInfo info = service.getRepaireInfo(id);
        long seconds = DateUtil.diffSecond(info.getBeginProcessTime(), new Date());
        info.setStatus(Constants.getStatus(info.getStatus()));
        info.setAddress(Constants.getAddress(info.getAddress()));
        model.addAttribute("repaireInfo",info);
        model.addAttribute("seconds",seconds);

        PicWord picWord = new PicWord();
        picWord.setCode("0"); // 只查询选项
        List<PicWord> picWords = picWordService.getPicWordList(picWord);
        model.addAttribute("picWords",picWords);
        
        return "engineer/engineer_detail";
    }
    @RequestMapping("/repairePic/list")
    @ResponseBody
    public Map<String,Object> searchRepairePic(@RequestParam("id") String repaireId) {
        Map<String,Object> result = ResponseData.getSuccessResult();
        List<String> data = new ArrayList<>();
        RepaireInfo repaireInfo = service.getRepaireInfo(repaireId);
        if(repaireInfo !=null && !StringUtils.isEmpty(repaireInfo.getPicAddress())){
            data.add(repaireInfo.getPicAddress());
        }
        RepairePic repairePic = new RepairePic();
        repairePic.setRepaireId(Long.parseLong(repaireId));
        List<String> collect =
            RepairePicService.searchRepairePic(repairePic).stream().map(repairePic1 -> repairePic1.getPicUrl())
                .collect(Collectors.toList());
        data.addAll(collect);
        result.put(ResponseData.DATA,data);
        return result;
    }

    @RequestMapping("/pending")
    public String pending(Model model,@RequestParam("userId")String userId){
        if(StringUtils.isEmpty(userId)){
            log.info("get userinfo error  userId is {}",userId);
            model.addAttribute("msg","系统错误请稍后重试...");
            return "warn";
        }
        Map<String,String> paramMap = new HashedMap();
        paramMap.put("currentId",userId);
        paramMap.put("status02","02");
        paramMap.put("status03","03");
        paramMap.put("status06","06");
        try{
            List<RepaireInfo> repaireInfoList = service.searchRepaireInfoPending(paramMap);
            model.addAttribute("repaireInfos",repaireInfoList);
            model.addAttribute("userId",userId);
            return "engineer/engineer_list";
        }catch (Exception e){
            log.error("com.weixin.web.EngineerController.pending error | ",e);
            model.addAttribute("msg","获取列表出错！");
            return "warn";
        }

    }

    @RequestMapping("/listAll")
    public String listAll(Model model,@RequestParam("userId")String userId){
        if(StringUtils.isEmpty(userId)){
            log.info("get userinfo error  userId is {}",userId);
            model.addAttribute("msg","系统错误请稍后重试...");
            return "warn";
        }
        Map<String,String> paramMap = new HashedMap();
        paramMap.put("currentId",userId);
        paramMap.put("status06","06");
        List<RepaireInfo> repaireInfoList = service.searchRepaireInfoByStatus06(paramMap);
        model.addAttribute("repaireInfos",repaireInfoList);
        model.addAttribute("userId",userId);
        return "engineer/engineer_list";
    }
    @RequestMapping("/list")
    public String list(Model model,@RequestParam("userId")String userId,HttpServletRequest request){
        if(StringUtils.isEmpty(userId)){
            userId = WXUserUtil.findCookie(request);
            if(StringUtils.isEmpty(userId)){
                log.info("get userinfo error  userId is {}",userId);
                model.addAttribute("msg","系统错误请稍后重试...");
                return "warn";
            }
        }
        Map<String,String> paramMap = new HashedMap();
        paramMap.put("currentId",userId);
        paramMap.put("status02","02");
        paramMap.put("status03","03");
        paramMap.put("status06","06");
        List<RepaireInfo> repaireInfoList = service.searchRepaireInfoByStatus(paramMap);
        model.addAttribute("repaireInfos",repaireInfoList);
        model.addAttribute("userId",userId);
        return "engineer/engineer_list";
    }

    @RequestMapping("/acceptRepaire/{id}")
    public String acceptRepaire(@PathVariable("id") String id,@RequestParam("time") String time,Model model,HttpServletRequest request ){
        RepaireInfo repaireInfo1 = service.getRepaireInfo(id);
        String userId = WXUserUtil.findCookie(request);
        if(!"06".equals(repaireInfo1.getStatus()) ||  StringUtils.isEmpty(userId) ){
            log.info("this work order is not acceptRepaire id is {},userId is {}",id,userId);
            model.addAttribute("msg","该工单已被接收...");
            return "warn";
        }
        RepaireInfo in = new RepaireInfo();
        in.setId(Long.parseLong(id));
        in.setStatus("02");
        in.setCurrentId(userId);
        Map inUser = new HashMap();
        inUser.put("userName",userId);
        User user = userService.findOne(inUser);
        in.setCurrentName(user.getDisplayName());
        in.setAcceptTime(new Date());
        in.setExpectTime(CommonUtils.encodeStr(time));
        service.update(in);
        RepaireInfo repaireInfoResult = service.getRepaireInfo(id);
        //  微信端提醒
        WXMsg wxMsg = new WXMsg();
        wxMsg.setAgentid(WxepConstants.REPAIRE_AGENT_ID);
        wxMsg.setMsgtype("text");
        wxMsg.setTouser(repaireInfoResult.getCreator());
        Text text = new Text();
        Dict dict = dictService.getDict(Constants.CREATOR_NOTIFY);
        String content = dict.getDictValue().
                replace("{expectTime}",CommonUtils.encodeStr(time)).replace("{workOrderId}",repaireInfoResult.getWorkOrderId());
        text.setContent(content);
        wxMsg.setText(text);
        try {
            weixinNotifyService.sendMsg(wxMsg,WxepConstants.REPAIRE_SECRET);
        } catch (Exception e) {
            log.error("weixinNotifyService.sendMsg error|",e);
        }
        return "forward:/weixin/engineer/list?userId="+userId;
    }
    // 开始服务
    @RequestMapping("/beginServer/{id}")
    public String beginServer(@PathVariable("id") String id,Model model,HttpServletRequest request){
        RepaireInfo repaireInfo1 = service.getRepaireInfo(id);
        String userId = WXUserUtil.findCookie(request);
        if(!"02".equals(repaireInfo1.getStatus())  ||  StringUtils.isEmpty(userId) ||  !userId.equals(repaireInfo1.getCurrentId())){
            log.info("this work order is not begin server id is {},userId is {}",id,userId);
            model.addAttribute("msg","您没有操作权限...");
            return "warn";
        }
        RepaireInfo repaireInfo = new RepaireInfo();
        repaireInfo.setId(Long.parseLong(id));
        repaireInfo.setBeginProcessTime(new Date());
        repaireInfo.setStatus("03");
        service.update(repaireInfo);
//        RepaireInfo repaireInfoResult = service.getRepaireInfo(id);
//        model.addAttribute("repaireInfo",repaireInfoResult);
        return "forward:/weixin/engineer/list?userId="+userId;
    }

    @RequestMapping("/endServer/{id}")
    public String endServer(@PathVariable("id") String id,Model model,HttpServletRequest request){
        RepaireInfo repaireInfo1 = service.getRepaireInfo(id);
        String userId = WXUserUtil.findCookie(request);
        if(!"03".equals(repaireInfo1.getStatus()) ||  StringUtils.isEmpty(userId) ||  !userId.equals(repaireInfo1.getCurrentId())){
            log.info("this work order is not end server id is {},userId is {}",id,userId);
            model.addAttribute("msg","您没有操作权限...");
            return "warn";
        }
        RepaireInfo repaireInfo = new RepaireInfo();
        repaireInfo.setId(Long.parseLong(id));
        repaireInfo.setEndProcessTime(new Date());
//        repaireInfo.setProcessSpecification(CommonUtils.encodeStr(processSpecification));
        repaireInfo.setStatus("04");
        service.update(repaireInfo);
        RepaireInfo result =service.getRepaireInfo(id);
        model.addAttribute("msg","工单号："+result.getWorkOrderId());
        Dict dict = dictService.getDict(Constants.TO_CUSTOMER_SATISFACTION);
        //  微信端提醒
        WXMsg wxMsg = new WXMsg();
        wxMsg.setAgentid(WxepConstants.REPAIRE_AGENT_ID);
        wxMsg.setMsgtype("text");
        wxMsg.setTouser(result.getCreator());
        Text text = new Text();
//        text.setContent("对我们的服务还满意吗？<a href=\"http://www.xutao.cf:8080/weixin/to_customer_satisfaction/"+result.getId()+"\">给TA一个评价吧！</a>说不定有惊喜哦~");
        text.setContent(dict.getDictValue().replace("{repairId}",id));
        wxMsg.setText(text);
        try {
            weixinNotifyService.sendMsg(wxMsg,WxepConstants.REPAIRE_SECRET);
        } catch (Exception e) {
            log.error("weixinNotifyService.sendMsg error|",e);
        }
        return "success";
    }

    public String  findCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie: cookies) {
            if(cookie.getName().equals("userId")){
                return cookie.getValue();
            }
        }
        return "";
    }

    @RequestMapping(value = "/showQr" )
    public String showQr(Model model,@RequestParam("userId")String userId){
//        String content = WxepConstants.qrContent.replace("{engineerId}",userId).
//                replace("{agentId}",WxepConstants.ENGINEER_AGENT_ID).replace("{corpId}",WxepConstants.CorpId);
        String content = WxepConstants.qrContent.replace("{engineerId}",userId);
        try {
            BufferedImage image = QRCodeUtil.createImage(content, null, false);
            ByteArrayOutputStream os = new ByteArrayOutputStream();//新建流。
            ImageIO.write(image, "PNG", os);//利用ImageIO类提供的write方法，将bi以png图片的数据模式写入流。
            byte b[] = os.toByteArray();//从流中获取数据数组。
            String baseStr = new BASE64Encoder().encode(b);
            model.addAttribute("qrPng",baseStr);
        } catch (Exception e) {
            log.error("com.weixin.web.EngineerController.showQr error | ",e);
        }
        return "engineer/qr";
    }

}
